package com.example.ceshi;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ceshi.Bean.DataDetail;
import com.example.ceshi.Bean.DetailBean;
import com.example.ceshi.Bean.LogisticsTraceDetails;
import com.example.ceshi.Bean.NowUserData;
import com.example.ceshi.SQLite.MySQLiteOpenHelper;
import com.example.ceshi.adapter.DetailAdapter;
import com.example.ceshi.adapter.DetailAdapter2;
import com.example.ceshi.utils.NetUtil;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Objects;

public class DetailActivity extends AppCompatActivity {

    private ImageView imageView;
    private TextView text_status;
    private TextView text_content;
    private TextView text_detail;
    private MySQLiteOpenHelper mySQLiteOpenHelper;


    private String strData = "";

    private String TAG2 = "ming";

    private DetailBean detailBean;

    private List<LogisticsTraceDetails> mBeanList;
    private ListView detailList;
    private DetailAdapter2 mDetailAdapter;

    //    浮现出获取子线程查询得到的数据
    private Handler mHandler = new Handler(Looper.myLooper()) {
        //        父线程接受信息
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0) {
                strData = (String) msg.obj;

                parseJsonData(strData);
                if (detailBean!=null&&Objects.equals(detailBean.getCode(), "200")) {

                    DataDetail dataDetail = detailBean.getData();
                    mBeanList = detailBean.getData().getLogisticsTraceDetails();

                    switch (dataDetail.getExpressCode()) {
                        case "SF":
                            imageView.setImageResource(R.drawable.sf);
                            break;
                        case "YTO":
                            imageView.setImageResource(R.drawable.yuantong);
                            break;
                        case "ZTO":
                            imageView.setImageResource(R.drawable.zhongtong);
                            break;
                        case "YUNDA":
                            imageView.setImageResource(R.drawable.yunda);
                            break;
                        case "STO":
                            imageView.setImageResource(R.drawable.shentong);
                            break;
                        case "TTKDEX":
                            imageView.setImageResource(R.drawable.tiantian);
                            break;
                        case "JD":
                            imageView.setImageResource(R.drawable.jingdong);
                            break;
                        case "EMS":
                            imageView.setImageResource(R.drawable.youzheng);
                            break;
                        case "DBKD":
                            imageView.setImageResource(R.drawable.debang);
                            break;
                        case "DBL":
                            imageView.setImageResource(R.drawable.debang);
                            break;
                        case "DBKY":
                            imageView.setImageResource(R.drawable.debang);
                            break;
                        case "JT":
                            imageView.setImageResource(R.drawable.jitu);
                            break;
                        default:
                            imageView.setImageResource(R.drawable.ic_notfound);
                            break;
                    }
                    text_status.setText(dataDetail.getLogisticsStatusDesc());
                    //        配置cotent内容
                    text_content.setText("上次更新：" + dataDetail.getTheLastTime());
                    //        配置详细信息
                    text_detail.setText(dataDetail.getExpressCompanyName() + " | " + dataDetail.getNumber());


                    mDetailAdapter = new DetailAdapter2(DetailActivity.this, mBeanList);
                    detailList.setAdapter(mDetailAdapter);

                    //查到详细星系
                    Toast.makeText(DetailActivity.this, "成功查询到信息", Toast.LENGTH_LONG).show();
                } else {
                    Button btn = findViewById(R.id.btn_check);
                    btn.setText("未查询到包裹");
                    text_status.setText("未查到数据");
                    //        配置cotent内容
                    text_content.setText("上次更新：" + "未查到数据");
                    //        配置详细信息
                    text_detail.setText("未查到数据" + " | " + "未查到数据");

                    //未查到详细信息
                    Toast.makeText(DetailActivity.this, "未查询到信息", Toast.LENGTH_LONG).show();
                }
                Log.d(TAG2, "封装的detailsbean:" + detailBean.toString());

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        Button btn = findViewById(R.id.btn_check);
        mySQLiteOpenHelper = new MySQLiteOpenHelper(DetailActivity.this);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                进行数据区操作

                if (String.valueOf(((Button) view).getText()).equals("加入我的包裹")) {
//                    数据库加
                    NowUserData.maxNum++;
                    NowUserData.dataDetailList.add(detailBean.getData());
                    long id = mySQLiteOpenHelper.insertExpressData(detailBean.getData().getNumber(), NowUserData.id);
                    if (id != -1) {
                        Toast.makeText(DetailActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                        ((Button) view).setText("移除包裹");
                        ((Button) view).setBackgroundColor(getResources().getColor(R.color.btn2));
                        ((Button) view).setTextColor(getResources().getColor(R.color.btn1));
                    } else {
                        Toast.makeText(DetailActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
                    }


                } else if (String.valueOf(((Button) view).getText()).equals("移除包裹")) {
//                    数据库减
                    int id = mySQLiteOpenHelper.deleteExpressData(detailBean.getData().getNumber(), NowUserData.id);
                    NowUserData.maxNum--;
                    for(int i=0;i<NowUserData.dataDetailList.size();i++){
                        if(NowUserData.dataDetailList.get(i).getNumber().equals(detailBean.getData().getNumber())){
                            NowUserData.dataDetailList.remove(i);
                        }
                    }

//                    NowUserData.dataDetailList.remove(id-1);
                    Log.d(TAG2,NowUserData.dataDetailList.toString()+"id: "+id);
//                    NowUserData.dataDetailList.remove(id);
                    if (id > 0) {
//                        NowUserData.dataDetailList.remove(id);
                        Toast.makeText(DetailActivity.this, "移除成功", Toast.LENGTH_SHORT).show();
                        ((Button) view).setText("加入我的包裹");
                        ((Button) view).setBackgroundColor(getResources().getColor(R.color.btn1));
                        ((Button) view).setTextColor(getResources().getColor(R.color.btn2));
                    } else {
                        Toast.makeText(DetailActivity.this, "移除失败", Toast.LENGTH_SHORT).show();
                    }

                }
            }
        });
        imageView = findViewById(R.id.iv_item);
        text_status = findViewById(R.id.tv_status);
        text_content = findViewById(R.id.tv_content);
        text_detail = findViewById(R.id.tv_detail);
        detailList = findViewById(R.id.lv_list);


        Bundle bundle = getIntent().getExtras();
        String number = bundle.getString("number");


        /*
          判断数据库是否有该包裹来进行按钮内容的改变
         */
        if (mySQLiteOpenHelper.selectExpressNoByExpressNo(number).equals("success")) {
            btn.setText("移除包裹");
            btn.setBackgroundColor(getResources().getColor(R.color.btn2));
            btn.setTextColor(getResources().getColor(R.color.btn1));
        }
        Log.d(TAG2,"detail中按钮的结果："+mySQLiteOpenHelper.selectExpressNoByExpressNo(number));
//
        getDetail(number);
    }


    //    将数据封装成JSON对象
    public void parseJsonData(String jsonStr) {

        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
//            DataDetail dataDetail =(DataDetail)jsonObject.getJSONObject("data");
            Gson gson = new Gson();
//            封装成的Bean对象 里面放的是物流的详细信息
            detailBean = gson.fromJson(jsonStr, DetailBean.class);
//            Log.d(TAG2,"开始执行了");
            Log.d(TAG2, detailBean.toString());

//            jsonObject.get
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //    子线程调用API查询数据
    public void getDetail(String number) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String stringFromNet = NetUtil.getDetails(number);

                Message message = new Message();
                message.what = 0;
                message.obj = stringFromNet;

                mHandler.sendMessage(message);
            }
        }).start();

//        Toast.makeText(this, "任务完成", Toast.LENGTH_LONG).show();
    }


}